package com.wm.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.wm.Global;
import com.wm.entity.RbacPerm;
import com.wm.entity.ResponseResult;
import com.wm.service.PermService;
import com.wm.util.Audience;
import com.wm.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
@Slf4j
@Order(2)
public class LoginFilter implements Filter {
    @Autowired
    private Audience audience;
    @Autowired
    private PermService permService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //判断是否登陆成功
        String url = req.getRequestURL().toString();
        String uri = req.getRequestURI();
        log.debug("url:{}",url);
        log.debug("uri:{}",uri);

        if (uri.endsWith("user/login")) {
            chain.doFilter(req, resp);
            return;
        }
        //不是访问的登录接口,判断是否已认证（判断是否带有合法有效的jwt）
        String jwt = req.getHeader("token");
        if (jwt == null) {
            ResponseResult<Object> result = new ResponseResult<>(411, "没有登陆");

            ObjectMapper objectMapper = new ObjectMapper();
            resp.getWriter().print(objectMapper.writeValueAsString(result));
            resp.getWriter().close();

        }else {
            //校验通过
            if (JwtUtil.verifyJwt(jwt,audience)) {
                //获取用户的所有权限
                int userId = JwtUtil.parseJwtForId(jwt, audience);
                List<RbacPerm> perms = Global.perms;
                if (perms == null) {
                    perms = permService.getPermsByUserId(userId);
                    Global.perms = perms;
                }

                for (RbacPerm perm : perms) {
                    if (perm.getLink().equals(url)) {
                        chain.doFilter(req, resp);
                        return;
                    }
                }

                ResponseResult<Object> result = new ResponseResult<>(412, "登陆已过期，请重新登陆");
                ObjectMapper objectMapper = new ObjectMapper();
                resp.getWriter().print(objectMapper.writeValueAsString(result));
                resp.getWriter().close();
            }
        }



    }
}
